package top.abrsm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;
import top.abrsm.entity.StudentEntity;
import top.abrsm.entity.bo.TokenBoUtil;
import top.abrsm.mapper.StudentMapper;
import top.abrsm.service.IStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.abrsm.util.ConstUtil;
import top.abrsm.util.StateEnum;
import top.abrsm.util.StateException;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 * 学生表 服务实现类
 * </p>
 *
 * @author WuZH
 * @since 2023-11-18
 */
@Service
@Slf4j
public class StudentServiceImpl extends ServiceImpl<StudentMapper, StudentEntity> implements IStudentService {

    @Resource
    private RestTemplate restTemplate;

    @Override
    public StudentEntity querySingle ( StudentEntity studentEntity ) {
        if ( studentEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        QueryWrapper<StudentEntity> queryWrapper = new QueryWrapper<> ();
        if ( studentEntity.getId () != null ) {
            queryWrapper.eq ( "stuId", studentEntity.getId () );
        }
        if ( studentEntity.getStuMobile () != null ) {
            queryWrapper.eq ( "stuMobile", studentEntity.getStuMobile () );
        }
        if ( studentEntity.getPassword () != null ) {
            queryWrapper.eq ( "password", studentEntity.getPassword () );
        }
        if ( studentEntity.getUnionid () != null ) {
            queryWrapper.eq ( "unionid", studentEntity.getUnionid () );
        }
        if ( studentEntity.getStuEmail () != null ) {
            queryWrapper.eq ( "stuEmail", studentEntity.getStuEmail () );
        }
        StudentEntity student = baseMapper.selectOne ( queryWrapper );
        return student;
    }

    @Override
    public StudentEntity updateSingle ( StudentEntity studentEntity ) {
        if ( studentEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        studentEntity.setChangeTime ( new Date () );
        int count = baseMapper.updateById ( studentEntity );
        if ( count == 0 ) {
            throw new StateException ( StateEnum.UPDATE_EXCE );
        }
        return studentEntity;
    }


    @Override
    public StudentEntity saveSingle ( StudentEntity studentEntity ) {
        if ( studentEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        studentEntity.setCreateTime ( new Date () );
        int insert = baseMapper.insert ( studentEntity );
        if ( insert == 0 ) {
            throw new StateException ( StateEnum.INSERT_EXCE );
        }
        return studentEntity;
    }

    /**
     * 社区平台通过微信扫码登录
     * 如果存在该openId则直接登录，否则注册后登录
     *
     * @param code：微信返回的一次性code码
     * @param state：网站前提提供的随机state字符串
     * @return
     */
//    @Override
//    public StudentEntity wxLogin ( String code, String state ) {
//        if ( code == null || state == null ) {
//            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
//        }
//        log.info ( "微信返回的code：[{}] 以及state：[{}]", code, state );
//        // 1. code获取token的url
//        String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + ConstUtil.WX_AppID + "&secret=" + ConstUtil.WX_AppSecret + "&code=" + code + "&grant_type=authorization_code";
//        // 获取的Token对象
//        String token = restTemplate.getForObject ( tokenUrl, String.class );
//        TokenBoUtil tokenBoUtil = JSON.parseObject ( token, TokenBoUtil.class );
//        log.info ( "微信返回的Token -> [{}]", tokenBoUtil );
//        // 2. token获取studentEntity
//        // 获取个人的信息
//        String userUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + tokenBoUtil.getAccess_token () + "&openid=" + tokenBoUtil.getOpenid ();
//        String resultStudentEntityStr = restTemplate.getForObject ( userUrl, String.class );
//        JSONObject jsonObject = ( JSONObject ) JSON.parse ( resultStudentEntityStr );
//        String nickName = String.valueOf ( jsonObject.get ( "nickname" ) );
//        StudentEntity resultStudentEntity = null;
//        if ( jsonObject != null && jsonObject.get ( "openid" ) != null ) {
//            try {
//                nickName = new String ( nickName.getBytes ( "ISO-8859-1" ), "UTF-8" );
//            } catch ( Exception e ) {
//                e.printStackTrace ();
//            }
//            resultStudentEntity = JSON.parseObject ( resultStudentEntityStr, StudentEntity.class );
//            resultStudentEntity.setAvatarUrl ( jsonObject.get ( "headimgurl" ).toString () );
//            resultStudentEntity.setNickName ( nickName );
//        }
//        log.info ( "微信返回的登录用户 -> [{}]", resultStudentEntity );
//        return resultStudentEntity;
//    }

}
